
package com.gitee.jmash.rbac.service;

import com.gitee.jmash.common.event.OperEvent;
import com.gitee.jmash.common.utils.UUIDUtil;
import com.gitee.jmash.core.orm.cdi.JpaTenantService;
import com.gitee.jmash.core.transaction.JakartaTransaction;
import com.gitee.jmash.rbac.entity.LogEntity;
import com.gitee.jmash.rbac.entity.LogEntity.LogPk;
import jakarta.enterprise.inject.Typed;
import jakarta.enterprise.inject.spi.EventMetadata;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.transaction.Transactional;
import jakarta.transaction.Transactional.TxType;
import jakarta.validation.executable.ValidateOnExecution;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 操作日志 rbac_log写服务.
 *
 * @author <a href="mailto:service@crenjoy.com">crenjoy</a>
 */
@Typed(LogWrite.class)
@Transactional(TxType.REQUIRED)
@JpaTenantService
@ValidateOnExecution
public class LogWriteBean extends LogReadBean implements LogWrite, JakartaTransaction {

  @Override
  @PersistenceContext(unitName = "WriteRbac")
  public void setEntityManager(EntityManager entityManager) {
    this.tem.setEntityManager(entityManager, true);
  }

  @Override
  public LogEntity insert(OperEvent event, EventMetadata metadata) {
    LogEntity logEntity = new LogEntity();
    logEntity.setCreateTime(LocalDateTime.now());
    logEntity.setPartition(LocalDate.now().getMonthValue());

    // 事件内容
    logEntity.setLogName(event.getLogName());
    logEntity.setLogLevel(event.getLogLevel().name());
    logEntity.setLogMsg(event.getLogMsg());
    logEntity.setLogContent(event.getLogContent());
    logEntity.setProxyIp(event.getProxyIp());
    logEntity.setUserIp(event.getUserIp());
    if (null != event.getPrincipal()) {
      logEntity.setCreateBy(UUIDUtil.fromString(event.getPrincipalName()));
    } else {
      logEntity.setCreateBy(UUIDUtil.emptyUUID());
    }
    logEntity.setEnvProps(metadata.getInjectionPoint().toString());

    logDao.persist(logEntity);
    return logEntity;
  }

  @Override
  public LogEntity delete(LogPk entityId) {
    LogEntity entity = logDao.removeById(entityId);
    return entity;
  }

  @Override
  public Integer batchDelete(int number) {
    LocalDateTime dateTime = LocalDateTime.now().minusYears(number);
    Integer result = logDao.batchDelete(dateTime);
    return result;
  }

}
